package com.whisperarts.financer.adapters;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.transaction.Category;

public class CategoryAdapter {
	private final Map<Integer, Category> categories;

	private final List<Category> sortedCategories;

	private final List<String> titlesList;

	private int depth = 0;

	private Category rootCategory;

	private String name;

	public CategoryAdapter() {
		categories = AccountsDAO.getCategories();
		sortedCategories = new ArrayList<Category>();
		titlesList = new ArrayList<String>();
	}
	
	public String[] getStructuredTitles(Category excludeCategory) {
		rootCategory = categories.get(0);

		sortedCategories.add(rootCategory);
		titlesList.add( rootCategory.getName());
		
		formStructure(rootCategory, excludeCategory);
		
		return titlesList.toArray(new String[0]);
	}
	
	/**
	 * Adds "-" to categories names according to their depth and puts them in correct order in items list
	 * @param rootCategory
	 */
	private void formStructure(Category rootCategory, Category excludeCategory) {
		int localDepth = depth++;
		for (Category category : rootCategory.getSub()) {
			if (category.equals(excludeCategory))
				continue;
			name = category.getName(); 
			for (int i = 0; i < localDepth; i++) {
				name = "−" + name;
			}
			name = name + (category.isIncome() ? " (+)" : " (-)");

			sortedCategories.add(category);
			titlesList.add( name );
			
			formStructure(category, excludeCategory);			
		}
		depth--;
	}

	public Category getCategoryByPosition(int position) {
		return sortedCategories.get(position);
	}

	public int getCategoryPosition(Category category) {
		return sortedCategories.indexOf(category);
	}
	
	public Category getCategoryById(Integer categoryId) {
		return categories.get(categoryId);
	}
}
